package com.yugao.fintech.framework.kafka.enable;

import com.yugao.fintech.framework.assistant.core.StringUtils;
import com.yugao.fintech.framework.core.utils.BeanRegistrationUtil;
import com.yugao.fintech.framework.mq.base.domain.MqEnable;
import com.yugao.fintech.framework.mq.base.enums.MqTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;

public class EnableKafkaRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {
    private static final Logger log = LoggerFactory.getLogger(EnableKafkaRegistrar.class);

    /**
     * 是否被执行过, 如果调用层启动类没有指定 {@link EnableKafka} 则会先执行且只执行一遍
     * rocketmq组件中的主类 上的{@link EnableKafka}注解，然后执行本类
     * <p>
     * 如果调用层启动类指定 {@link EnableKafka},则会先执行且只执行一遍, 执行本类
     * 使用 {@link EnableKafkaRegistrar#isExecuted} 作为标记
     */
    private static Boolean isExecuted = false;

    private Environment environment;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        try {
            if (isExecuted) {
                return;
            }
            isExecuted = true;
            Boolean enableValue = getEnableRocketmqValue(importingClassMetadata);
            if (enableValue != null && enableValue) {
                MqEnable.addEnableMq(MqTypeEnum.KAFKA);
            }

            String beanId = StringUtils.uncapitalize(EnableKafkaBeanDefinitionRegistryPostProcessor.class.getSimpleName());
            BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, beanId, EnableKafkaBeanDefinitionRegistryPostProcessor.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected Boolean getEnableRocketmqValue(AnnotationMetadata importingClassMetadata) {
        Map<String, Object> attributes = importingClassMetadata
                .getAnnotationAttributes(EnableKafka.class.getName());
        return (Boolean) attributes.get("value");
    }
}
